In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.
Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.
The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.
# Load pickled data
import pickle
# TODO: Fill this in based on where you saved the training and testing data
training_file = "train.p"
validation_file="valid.p"
testing_file = "test.p"
with open(training_file, mode='rb') as f:
train = pickle.load(f)
with open(validation_file, mode='rb') as f:
valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
test = pickle.load(f)
X_train1, y_train1 = train['features'], train['labels']
X_valid1, y_valid1 = valid['features'], valid['labels']
X_test1, y_test1 = test['features'], test['labels']
The pickled data is a dictionary with 4 key/value pairs:
'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.'sizes' is a list containing tuples, (width, height) representing the original width and height the image.'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGESComplete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.
### Replace each question mark with the appropriate value.
### Use python, pandas or numpy methods rather than hard coding the results
# TODO: Number of training examples
n_train = len(X_train1)
# TODO: Number of testing examples.
n_valid = len(X_valid1)
# TODO: Number of testing examples.
n_test = len(X_test1)
# TODO: What's the shape of an traffic sign image?
image_shape = X_train1[0].shape
# TODO: How many unique classes/labels there are in the dataset.
n_classes = len(list(set(y_test1)))
print("Number of training examples =", n_train)
print("Number of validdation examples =", n_valid)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.
The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.
NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections.
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
import numpy as np
import re
import cv2
# Visualizations will be shown in the notebook.
%matplotlib inline
def get_set_num(y):
tr_num={}
tr_list={}
for i in list(set(y)):
tr_num[i]=(y==i).sum()
a=np.argwhere(y==i)
b=[]
for k in a:
for j in k:
b.append(j)
tr_list[i]=b
return tr_num, tr_list
def get_sign_desp():
fp=open("signnames.csv")
lines=fp.readlines()
#print(lines[1:])
sign_list=[]
for i in lines[1:]:
#print (i)
li=re.split(r',',i)
sign_list.append(li[1].strip())
return sign_list
def get_lum(x):
if(len(x.shape)>2):
return int(np.average(x[:,:,0]*0.3+x[:,:,1]*0.6+x[:,:,2]*0.1))
else:
return int(np.average(x[:,:]))
def get_one_data_set(X, y, label, index):
tr_list=np.argwhere(y==label).flatten()
xx=X[tr_list[index]].squeeze()
yy=y[tr_list[index]].squeeze()
return xx,yy
def get_data_set(X, y, label, sqz):
tr_list=np.argwhere(y==label).flatten()
if(sqz):
xx=[i.squeeze() for i in X[tr_list]]
yy=[i.squeeze() for i in y[tr_list]]
else:
xx=np.copy(X[tr_list])
yy=np.copy(y[tr_list])
return xx,yy
def get_min_max(xx):
lum_list=[get_lum(x) for x in xx]
max_lum=np.max(lum_list)
min_lum=np.min(lum_list)
return min_lum, max_lum, lum_list
def show_data_info(X, y,title,col):
lum_min=[]
lum_max=[]
plt.subplot(3,1,col)
plt.hist(y, bins="auto")
plt.title(title+":data set size:")
plt.ylabel("sample count")
plt.xlabel("sample class")
plt.show()
if (0):
for label in range(43):
xx,yy=get_data_set(X,y,label,1)
lum_min.append(get_min_max(xx)[0])
lum_max.append(get_min_max(xx)[1])
plt.hist2d(lum_min, lum_max)
plt.colorbar()
plt.title(title+":min/max")
plt.show()
# rand =0 let view the traffice of first eight track in each class
# rand =1 view randomly picked 8 images from each class
def show_sign(x,y,prefix, nrows, ncols, label, rand):
tr_list=np.argwhere(y==label).flatten()
if(rand):
np.random.shuffle(tr_list)
else:
# German Traffic Sign Data Set has a track size of 30
track_size=30
tr_list=tr_list.reshape(int(len(tr_list)/track_size),track_size).T
tr_list=tr_list.flatten()
#print (x[tr_list])
xx,yy=get_data_set(x,y,label,1)
max_lum,min_lum, lum_list=get_min_max(xx)
print (label, sign_desp[label], "Size:", len(xx), \
"Max/Min/Average:", min_lum, max_lum, int(np.average(lum_list)))
plt.figure(figsize=(8,6))
for i in range(nrows):
for j in range (ncols):
plt.subplot(nrows,ncols,(i)*ncols+1+j)
n=tr_list[i*ncols+j]
m=i*ncols+j
plt.title(str(label)+":"+str(n))
plt.axis("off")
if(len(xx[m].shape)>2 and xx[m].shape[2]==3):
plt.imshow(xx[m])
cv2.imwrite(prefix+"/class_"+str(label)+"_"+str(n)+".jpg", xx[m])
else:
#plt.imshow(xx[m])
plt.imshow(np.dstack((xx[m],xx[m],xx[m])))
cv2.imwrite(prefix+"/class_"+str(label)+"_"+str(n)+".jpg", np.dstack((xx[m],xx[m],xx[m])))
plt.show()
global sign_desp
# plot data set information
sign_desp=get_sign_desp()
show_data_info(X_train1,y_train1,"train",1)
show_data_info(X_valid1,y_valid1,"valid",3)
show_data_info(X_test1,y_test1,"test",2)
# plot traffic sign images
if (1):
print ("Training data set, 8 random selected images for each class")
for i in range(43):
show_sign(X_train1, y_train1, "train_ori", 1, 8, i, 1)
print ("Validation data set, 8 random selected images for each class")
for i in range(43):
show_sign(X_valid1, y_valid1, "valid_ori", 1, 8, i, 1)
Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.
The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!
With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission.
There are various aspects to consider when thinking about this problem:
Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.
Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.
def color2gray(x):
image2 = (x[:,:,0]*0.3+x[:,:,1]*0.6+x[:,:,2]*0.1)
image = image2.astype("uint8")
image = np.reshape(image, [32, 32, 1])
return image
def denorm_one_img(img1):
img1=(img1+1.0)*127.5
img1=img1.astype("uint8")
return img1
def denorm_image(X, use_gray, use_norm):
if(use_norm):
Y=(X+1)*127.5
else:
Y=X
#clip to [0, 255]
Y[:,:,:][Y[:,:,:]>255.0] = 255
Y[:,:,:][Y[:,:,:]<0.0] = 0
if(use_gray):
Y=Y.squeeze()
Y=np.stack((Y,Y,Y),axis=-1)
nY=Y.astype("uint8")
return nY
# use hist normalize to make input data zero mean
def norm_image(X, gray, norm):
nX=[]
for i in range(len(X)):
x = X[i].squeeze()
if(gray):
image = color2gray(x)
image = cv2.equalizeHist(image)
if(norm):
image = (image/127.5-1.0)
image = np.reshape(image, [32, 32, 1])
else:
image = np.copy(x)
if(norm):
image = (image/127.5-1.0)
image = np.reshape(image, [32, 32, 3])
nX.append(image)
Y=np.array(nX)
return Y
def augment_brightness(image):
prob=np.random.randint(4)
hi=aug_spec["brightness"][1]
lo=aug_spec["brightness"][0]
random_bright = lo+np.random.uniform()*(hi-lo)
#random_bright = -random_bright
if(prob==0):
image1 = (image+1.0)*random_bright-1.0
else:
image1 = image*1.0
image1[:,:][image1[:,:]>1.0] = 1.0
image1[:,:][image1[:,:]<-1.0] = -1.0
return image1
def transform_image(ori_image,ang_range,trans_range):
pad=16
image=cv2.copyMakeBorder(ori_image, pad,pad,pad,pad,cv2.BORDER_REPLICATE)
# Rotation
ang_rot = np.random.uniform(ang_range)-ang_range/2
#ang_rot = 5
rows,cols = image.shape
# Rotation
sc0=aug_spec["scale"][0]
sc1=aug_spec["scale"][1]
sc = sc0+np.random.uniform()*(sc1-sc0)
Rot_M = cv2.getRotationMatrix2D((cols/2,rows/2),ang_rot,sc)
# Translation
tr_x = trans_range*np.random.uniform()-trans_range/2
tr_y = trans_range*np.random.uniform()-trans_range/2
Trans_M = np.float32([[1,0,tr_x],[0,1,tr_y]])
image = cv2.warpAffine(image,Rot_M,(cols,rows))
image = cv2.warpAffine(image,Trans_M,(cols,rows))
image = image[pad:pad+32, pad:pad+32]
return image
def flip_image(image, label):
image=image.squeeze()
if(label not in [0,1,2,3,4,5,6,7,8,14,19,20,24,33,34,36,37,38,39]):
if(np.random.randint(4)==0):
image=cv2.flip(image,1)
image=image.reshape([32,32,1])
return image
def augment_image(image):
#[+/-2], 15 degree
ang_range,trans_range = aug_spec["angle"], aug_spec["tran"]
image=image.squeeze()
image = augment_brightness(image)
image = transform_image(image,ang_range,trans_range)
image=image.reshape([32,32,1])
return image
# show one image per each class, to view clearly use hist normalization
def show_class_images(X, y, show, name, hist=1):
print(name, "Data Set Size,Max,Min,Mean:", len(X), np.max(X), np.min(X), np.mean(X))
tr_num,tr_list=get_set_num(y)
if(show==1):
plt.figure(dpi=80,figsize=(8*2, 6*2))
for i in range(43):
plt.subplot(6, 8, 1+i)
plt.axis("off")
idx=tr_list[i][0]
plt.title(str(i)+":"+str(int((np.max(X[idx])+1)*127.5)))
img=denorm_image(X[idx], use_gray, use_norm)
img=cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
if(hist==1):
img=cv2.equalizeHist(img)
plt.imshow(cv2.cvtColor(img,cv2.COLOR_GRAY2RGB))
plt.show()
def add_aug_images(X_train, y_train, number):
X_train_list=X_train.tolist()
y_train_list=y_train.tolist()
tr_num,tr_list=get_set_num(y_train)
for i in tr_num.keys():
num=max(0,number-tr_num[i])
if(num>0):
print ("Add %d samples for %d %s class"%(num, i, sign_desp[i]))
for j in range(num):
idx=tr_list[i][j%tr_num[i]]
img1=X_train[idx]
img2=augment_image(img1)
img2=flip_image(img2,y_train[idx])
X_train_list.append(img2)
y_train_list.append(i)
X_train=np.array(X_train_list,dtype="float64")
y_train=np.array(y_train_list,dtype="float64")
return X_train, y_train, tr_num
def show_aug_images(X_train, y_train):
for label in range(43):
tr_list=np.argwhere(label==y_train).flatten()
img1=X_train[tr_list[0]]
yy=y_train[tr_list[0]]
print(label, get_sign_desp()[label], img1.shape,img1.dtype)
plt.figure(dpi=80,figsize=(8*2, 6*2))
plt.subplot(1,8,1)
plt.imshow(denorm_one_img(img1.squeeze()), cmap="gray")
for i in range(7):
plt.subplot(1,8,i+2)
plt.axis("off")
img2=augment_image(img1)
img2=flip_image(img2, label)
plt.imshow(denorm_one_img(img2.squeeze()), cmap="gray")
plt.show()
def gen_new_batch(X,y, aug_size):
nX=[]
ny=[]
for i in range(len(X)):
for k in range(aug_size):
if(k>0):
img1=augment_image(X[i])
img1=flip_image(img1,y[i])
else:
img1=np.copy(X[i])
nX.append(img1)
ny.append(y[i])
return nX, ny
### Preprocess the data here. Preprocessing steps could include normalization, converting to grayscale, etc.
### Feel free to use as many code cells as needed.
use_gray=1
use_norm=1
aug_spec={"brightness":[0.9,1.1],
"angle":5,
"tran":4,
"scale":[0.75,1.5]}
if(use_gray):
input_depth=1
else:
input_depth=3
X_train2=norm_image(X_train1,use_gray, use_norm)
y_train2=np.copy(y_train1)
X_valid=norm_image(X_valid1,use_gray, use_norm)
X_test=norm_image(X_test1,use_gray, use_norm)
y_valid=np.copy(y_valid1)
y_test=np.copy(y_test1)
show_class_images(X_train2, y_train2, 0, name="Train", hist=0)
show_class_images(X_valid, y_valid, 0, name="Valid", hist=0)
show_class_images(X_test, y_test, 0, name="Test", hist=0)
np.random.seed(1234)
# add augmented images, each class has at least 1000
X_train3, y_train3, tr_num3=add_aug_images(X_train2, y_train2, 1000)
show_class_images(X_train3, y_train3, 1, name="Augmented Train", hist=0)
show_aug_images(X_train3, y_train3)
from sklearn.utils import shuffle
#X_train, y_train=shuffle(X_train2, y_train2)
X_train, y_train=shuffle(X_train3, y_train3)
print("Train data set image no: ", (X_train3.shape[0]))
### Define your architecture here.
### Feel free to use as many code cells as needed.
import tensorflow as tf
EPOCHS = 75
BATCH_SIZE = 128
from tensorflow.contrib.layers import flatten
tf.reset_default_graph()
global conv1_W
global conv1_b
global conv2_W
global conv2_b
global fc1_W
global fc1_b
global fc2_W
global fc2_b
global fc3_W
global fc3_b
nn_spec1={"conv1":[5,5,1,6],
"conv2":[5, 5, 6, 16],
"fc1":[400,120],
"fc2":[120,84],
"fc3":[84,43]
}
nn_spec2={"conv1":[5,5,1,8],
"conv2":[5,5,8,16],
"fc1":[400,128],
"fc2":[128,256],
"fc3":[256,43]
}
nn_spec=nn_spec2
def LeNet(x, keep_prob):
# Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer
mu = 0
sigma = 0.1
# SOLUTION: Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6.
conv1_W = tf.Variable(tf.truncated_normal(shape=nn_spec["conv1"], mean = mu, stddev = sigma), name='conv1_W')
conv1_b = tf.Variable(tf.zeros(nn_spec["conv1"][3]), name='conv1_b')
conv1 = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID') + conv1_b
# SOLUTION: Activation.
conv1 = tf.nn.relu(conv1)
# SOLUTION: Pooling. Input = 28x28x6. Output = 14x14x6.
conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
# SOLUTION: Layer 2: Convolutional. Output = 10x10x16.
conv2_W = tf.Variable(tf.truncated_normal(shape=nn_spec["conv2"], mean = mu, stddev = sigma), name='conv2_W')
conv2_b = tf.Variable(tf.zeros(nn_spec["conv2"][3]), name='conv2_b')
conv2 = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID') + conv2_b
# SOLUTION: Activation.
conv2 = tf.nn.relu(conv2)
# SOLUTION: Pooling. Input = 10x10x16. Output = 5x5x16.
conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
# SOLUTION: Flatten. Input = 5x5x16. Output = 400.
fc0 = flatten(conv2)
fc0 = tf.nn.dropout(fc0, keep_prob)
# SOLUTION: Layer 3: Fully Connected. Input = 400. Output = 120.
fc1_W = tf.Variable(tf.truncated_normal(shape=nn_spec["fc1"], mean = mu, stddev = sigma), name='fc1_W')
fc1_b = tf.Variable(tf.zeros(nn_spec["fc1"][1]), name='fc1_b')
fc1 = tf.matmul(fc0, fc1_W) + fc1_b
# SOLUTION: Activation.
fc1 = tf.nn.relu(fc1)
fc1 = tf.nn.dropout(fc1, keep_prob)
# SOLUTION: Layer 4: Fully Connected. Input = 120. Output = 84.
fc2_W = tf.Variable(tf.truncated_normal(shape=nn_spec["fc2"], mean = mu, stddev = sigma), name='fc2_W')
fc2_b = tf.Variable(tf.zeros(nn_spec["fc2"][1]), name='fc2_b')
fc2 = tf.matmul(fc1, fc2_W) + fc2_b
# SOLUTION: Activation.
fc2 = tf.nn.relu(fc2)
fc2 = tf.nn.dropout(fc2, keep_prob)
# SOLUTION: Layer 5: Fully Connected. Input = 84. Output = 10.
fc3_W = tf.Variable(tf.truncated_normal(shape=nn_spec["fc3"], mean = mu, stddev = sigma), name='fc3_W')
fc3_b = tf.Variable(tf.zeros(nn_spec["fc3"][1]), name='fc3_b')
logits = tf.matmul(fc2, fc3_W) + fc3_b
layer_list = [conv1, conv2, fc0, fc1, fc2, logits]
return layer_list
A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected,
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.
x = tf.placeholder(tf.float32, (None, 32, 32, input_depth))
y = tf.placeholder(tf.int32, (None))
keep_prob = tf.placeholder(tf.float32)
rate = tf.placeholder(tf.float32)
one_hot_y = tf.one_hot(y, 43)
layer_list = LeNet(x,keep_prob)
[conv1, conv2, fc0, fc1, fc2, logits]=layer_list
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=one_hot_y)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation)
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
def evaluate(X_data, y_data):
num_examples = len(X_data)
total_accuracy = 0
total_loss = 0
sess = tf.get_default_session()
for offset in range(0, num_examples, BATCH_SIZE):
batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
accuracy, loss = sess.run([accuracy_operation,loss_operation], feed_dict={x: batch_x, y: batch_y, keep_prob:1.0})
total_accuracy += (accuracy * len(batch_x))
total_loss += (loss * len(batch_x))
return total_accuracy / num_examples, total_loss/num_examples
import time
import operator
def get_time():
t = time.time()
return t
def train_process(target, iter, aug_size, bsize, prob, t_rate, restore):
global saver
global X_train
global y_train
np.random.seed(1234)
acc_list=[]
t0=get_time()
log_name="train_log_"+str(aug_size)+".csv"
fp = open(log_name,"w")
with tf.Session() as sess:
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())
if(restore==True):
print("Loading variables from %s." % "./lenet")
saver.restore(sess,"./lenet")
else:
print("Initialize variables")
sess.run(tf.global_variables_initializer())
num_examples = len(X_train)
print("Training...")
print()
print("EPOC, Time, Train Acc, Loss, Valid acc, Loss, Test Acc, Loss")
fp.write("EPOC, Time, Train Acc, Loss, Valid acc, Loss, Test Acc, Loss\n")
for i in range(iter):
t1=get_time()
X_train, y_train = shuffle(X_train, y_train)
for offset in range(0, num_examples, bsize):
end = offset + bsize
batch_x, batch_y = X_train[offset:end], y_train[offset:end]
batch_x, batch_y = gen_new_batch(batch_x, batch_y,aug_size)
sess.run(training_operation, feed_dict={x: batch_x, y: batch_y, \
rate: t_rate, keep_prob: prob})
train_accuracy, train_loss = evaluate(X_train, y_train)
validation_accuracy, valid_loss = evaluate(X_valid, y_valid)
test_accuracy, test_loss = evaluate(X_test, y_test)
acc_list.append([train_accuracy,validation_accuracy, test_accuracy])
t2=get_time()
fp.write("%d, %.3f ,%.5f,%.3f, %.5f, %.3f, %.5f, %.3f, \n" \
%(i,(t2-t1), \
train_accuracy,train_loss,\
validation_accuracy, valid_loss,\
test_accuracy, test_loss))
print("%d, %.3f ,%.5f,%.3f, %.5f, %.3f, %.5f, %.3f, " \
%(i,(t2-t1), \
train_accuracy,train_loss,\
validation_accuracy, valid_loss,\
test_accuracy, test_loss))
if(validation_accuracy>target):
#acc_list.append([train_accuracy,validation_accuracy, test_accuracy]*(iter-1-i))
break
saver.save(sess, './lenet')
print("Model saved")
fp.close()
t2=get_time()
print("Used %.2f min, epoc:%d, Final Eval/Valid/Test Accuarcy:%.5f, %.5f %.5f"\
%((t2-t0)/60.0, len(acc_list), acc_list[-1][0],acc_list[-1][1],acc_list[-1][2]))
return acc_list
target=0.99
iter=75
saver = tf.train.Saver()
acc_list=[]
aug_size=2
prob=0.80
t_rate = 0.0005
def print_train_info():
print("Hyperparameters overview:")
print("Maximum Epocs", iter)
print("Traing rate:", t_rate)
print("Target valid accuracy[stop once hit]:", target)
print("Augmented Train Data Set size:",X_train.shape[0])
print("Valid Data Set size:",X_valid.shape[0])
print("Test Data Set size:",X_test.shape[0])
print("[Augmented Train Data Set parameters]")
print("Number of augmented image ratio during traing:", aug_size-1)
for i in list(aug_spec.keys()):
print (i, ":", aug_spec[i])
ke=list(nn_spec.keys())
print("[NN specification]")
ke.sort()
w=0
n=0
for i in ke:
w=np.multiply.reduce(nn_spec[i])+nn_spec[i][-1]
print (i, ":", nn_spec[i], ". Weights:", w)
print("Keep Prob of FC1, FC2, FC3:", prob)
bsize=int(BATCH_SIZE/aug_size)
iter=75
aug_size=4
print_train_info ()
restore=False
acc_list1 = train_process(target,iter,aug_size, bsize, prob, t_rate, restore=restore)
acc_list.append(acc_list1)
var_list=["conv1_W", "conv1_b", "conv2_W","conv2_b", "fc1_W", "fc2_W", "fc3_W","fc1_b", "fc2_b", "fc3_b"]
#var_list=["conv1_W", "conv1_b", "conv2_W","conv2_b", "fc1_W", "fc2_W", "fc3_W"]
def restore_tensor(checkpoint_file='./lenet'):
tensor_list={}
with tf.Session() as session:
saver = tf.train.Saver()
saver.restore(session, checkpoint_file)
#print(session.run(tf.global_variables()))
for i in var_list:
n=i+":0"
t = session.graph.get_tensor_by_name(n)
#print("Saved TF var:", t.name, "Mean/Std:",np.mean(t.eval()),np.std(t.eval()))
tensor_list[i]=t
#print (t)
return tensor_list
def reset():
tf.reset_default_graph()
#reset()
res_tensor=restore_tensor()
#inspect_checkpoint --file_name='./lenet'
from sklearn.metrics import classification_report
def predict(X_data):
sess = tf.get_default_session()
res = sess.run(tf.argmax(logits,1), feed_dict={x: X_data, keep_prob:1.0})
return res
def plot_curve(curves,T):
lab=["eval","val","test"]
bsize=[2,4,8,1]
plt.figure(figsize=(8,6))
plt.title("Prediction Accuracy")
for i in range(len(curves)):
curve=curves[i]
x=range(len(curve))
c1=np.array(curve)
title=T+str(bsize[i])
plt.subplot(1,len(curves),i+1)
for k in range(3):
plt.plot(x,c1[:,k],linestyle="-", label=lab[k])
plt.legend(loc='upper left',title=title)
plt.show()
with tf.Session() as sess:
#saver.restore(sess, tf.train.latest_checkpoint('.'))
saver = tf.train.Saver()
saver.restore(sess, './lenet')
test_accuracy, test_loss = sess.run([accuracy_operation, loss_operation], feed_dict={x: X_test, y: y_test, keep_prob: 1.0})
valid_accuracy, valid_loss = sess.run([accuracy_operation, loss_operation], feed_dict={x: X_valid, y: y_valid, keep_prob: 1.0})
train_accuracy, train_loss = sess.run([accuracy_operation, loss_operation], feed_dict={x: X_train, y: y_train, keep_prob: 1.0})
predictions=predict(X_test)
expected=y_test
rept = classification_report(expected, predictions)
print("Test Accuracy and Loss = %.3f, %.3f"%(test_accuracy, test_loss))
print (rept)
predictions=predict(X_valid)
expected=y_valid
rept = classification_report(expected, predictions)
print("valid Accuracy and loss = %.3f, %.3f"%(valid_accuracy,valid_loss ))
print (rept)
predictions=predict(X_train)
expected=y_train
rept = classification_report(expected, predictions)
print("Train Accuracy and loss = %.3f, %.3f"%(train_accuracy,train_loss ))
print (rept)
plot_curve(acc_list,"Batch size:")
import tensorflow as tf
saver = tf.train.Saver()
print("Check Train/Valid/Test Accuarcy for each class")
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('.'))
accs=[]
lab=["Train","Valid","Test"]
for k in range(3):
accs1=[]
X_in, y_in=[[X_train,y_train],[X_valid,y_valid],[X_test,y_test]][k]
for i in range(43):
XX,yy=get_data_set(X_in, y_in, i,0)
size=len(XX)
pred_res = predict(XX[:size])
acc=(pred_res==i).sum()
accs1.append(acc*1.0/size)
#print(accs1)
accs.append(accs1)
print ("Done")
def get_class_size():
cs=[]
for k in range(3):
cs1=[]
X_in, y_in=[[X_train,y_train],[X_valid,y_valid],[X_test,y_test]][k]
for i in range(43):
XX,yy=get_data_set(X_in, y_in, i,0)
cs1.append(len(XX))
cs.append(cs1)
return cs
cs=get_class_size()
plt.figure(dpi=80,figsize=(8*2, 6))
plt.subplot(1,3,1)
for k in range(len(accs)):
accs1=np.array(accs[k])
cs1=np.array(cs[k],dtype="float32")
cn1=cs1/cs1.sum()
plt.plot(range(len(accs1)),cn1,linestyle="--", label=lab[k])
plt.legend(title="Classs ratio")
plt.subplot(1,3,2)
for k in range(len(accs)):
accs1=np.array(accs[k])
err1=1.0-accs1
plt.plot(range(len(accs1)),err1,linestyle="-", label=lab[k])
plt.legend(title="Classs error rate")
plt.subplot(1,3,3)
for k in range(len(accs)):
accs1=np.array(accs[k])
cs1=np.array(cs[k],dtype="float32")
cn1=(1-accs1)*cs1
plt.plot(range(len(accs1)),cn1,linestyle="--", label=lab[k])
plt.legend(title="Classs error number")
plt.savefig("class_error.png")
plt.show()
To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.
You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.
def resize_img(img):
pad=5
img=mpimg.imread("examples/test0.jpg")
img=cv2.copyMakeBorder(img, pad,pad,pad,pad,cv2.BORDER_CONSTANT, value=0)
plt.imshow(img)
plt.show()
img=cv2.resize(img,(32,32))
plt.imshow(img)
plt.show()
mpimg.imsave("examples/test7.jpg",img)
return img
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
num=8
X_t1=[]
y_t1=[]
if (1):
y_t1=[28,4,28,33,1,1,18,28]
print("Web images")
for i in range(num):
n="examples/test"+str(i)+".jpg"
img=mpimg.imread(n)
plt.subplot(1,num,i+1)
plt.imshow(img)
X_t1.append(np.copy(img))
else:
fp=open("tri_image.txt")
lines=fp.readlines()
for i in lines:
li=re.search(r'class_(.*?)_(.*?).jpg',i.strip())
cl=li.group(1)
img=mpimg.imread(i.strip())
X_t1.append(np.copy(img))
y_t1.append(int(cl))
plt.show()
### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.
import matplotlib.image as mpimg
X_t=norm_image(X_t1,1, 1)
y_t=np.copy(y_t1)
print("Normalized images")
print("Mean/Max/Min:", np.mean(X_t), np.max(X_t), np.min(X_t))
for i in range(num):
plt.subplot(1,num,i+1)
plt.title("T:"+str(y_t[i]))
plt.imshow(denorm_image(X_t[i],1,1))
plt.show()
print("Train examples")
for i in range(num):
plt.subplot(1,num,i+1)
tr_list=np.argwhere(y_t[i]==y_train).flatten()
xx=X_train[tr_list[10]]
yy=y_train[tr_list[10]]
plt.imshow(denorm_image(xx,1,1))
plt.show()
### Calculate the accuracy for these 5 new images.
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.
import tensorflow as tf
saver = tf.train.Saver()
print("Check Prediction Accuarcy")
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('.'))
pred_res = predict(X_t)
t = (pred_res == y_t).sum()
print("Predictions:",pred_res)
print("Actural:",y_t)
print("Accuracy:",t/len(X_t))
print ("Done")
For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.
The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.
tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.
Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tk.nn.top_k is used to choose the three classes with the highest probability:
# (5, 6) array
a = np.array([[ 0.24879643, 0.07032244, 0.12641572, 0.34763842, 0.07893497,
0.12789202],
[ 0.28086119, 0.27569815, 0.08594638, 0.0178669 , 0.18063401,
0.15899337],
[ 0.26076848, 0.23664738, 0.08020603, 0.07001922, 0.1134371 ,
0.23892179],
[ 0.11943333, 0.29198961, 0.02605103, 0.26234032, 0.1351348 ,
0.16505091],
[ 0.09561176, 0.34396535, 0.0643941 , 0.16240774, 0.24206137,
0.09155967]])
Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:
TopKV2(values=array([[ 0.34763842, 0.24879643, 0.12789202],
[ 0.28086119, 0.27569815, 0.18063401],
[ 0.26076848, 0.23892179, 0.23664738],
[ 0.29198961, 0.26234032, 0.16505091],
[ 0.34396535, 0.24206137, 0.16240774]]), indices=array([[3, 0, 5],
[0, 1, 4],
[0, 5, 1],
[1, 3, 5],
[1, 4, 3]], dtype=int32))
Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.
def get_softmax(X):
with tf.Session() as sess:
saver.restore(sess, './lenet')
sm=tf.nn.softmax(logits)
a=sess.run(sm, feed_dict={x:X, keep_prob:1.0})
ret=sess.run(tf.nn.top_k(tf.constant(a), k=5))
return ret, a
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web.
### Feel free to use as many code cells as needed.
with tf.Session() as sess:
saver.restore(sess, './lenet')
(m,n), a=get_softmax(X_t[:8])
plt.figure(figsize=(16,6),dpi=80)
# print Class, image no, the rank in the softmax output
# rank=-1 means it is not in the top 5 choices. rank=0 means it has max possibility.
for i in range(len(a)):
plt.subplot(2,5,i+1)
try:
rank=n[i].tolist().index(y_t[i])
except:
rank=-1
#print (rank)
plt.title("Class"+str(y_t[i])+",Image:"+str(i)+",rank:"+str(rank))
plt.plot(range(len(a[i])), a[i])
plt.show()
This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.
Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the LeNet lab's feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.
For an example of what feature map outputs look like, check out NVIDIA's results in their paper End-to-End Deep Learning for Self-Driving Cars in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.
Your output should look something like this (above)
### Visualize your network's feature maps here.
### Feel free to use as many code cells as needed.
# image_input: the test image being fed into the network to produce the feature maps
# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer
# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output
# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry
def outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1 ,plt_num=1):
# Here make sure to preprocess your image_input in a way your network expects
# with size, normalization, ect if needed
# image_input =
# Note: x should be the same name as your network's tensorflow data placeholder variable
# If you get an error tf_activation is not defined it maybe having trouble accessing the variable from inside a function
activation = tf_activation.eval(session=sess,feed_dict={x : image_input})
featuremaps = activation.shape[3]
for i in range(len(image_input)):
plt.figure(plt_num, figsize=(15,15), dpi=80)
for featuremap in range(featuremaps):
vmin = np.min(activation[i,:,:,featuremap])
vmax = np.max(activation[i,:,:,featuremap])
#print (vmin, vmax)
plt.subplot(6,10, featuremap+1) # sets the number of feature maps to show on each row and column
plt.axis("off")
if activation_min != -1 & activation_max != -1:
plt.imshow(activation[i,:,:, featuremap], interpolation="nearest", vmin =activation_min, vmax=activation_max, cmap="gray")
elif activation_max != -1:
plt.imshow(activation[i,:,:, featuremap], interpolation="nearest", vmax=activation_max, cmap="gray")
elif activation_min !=-1:
plt.imshow(activation[i,:,:, featuremap], interpolation="nearest", vmin=activation_min, cmap="gray")
else:
plt.imshow(activation[i,:,:, featuremap], interpolation="nearest", cmap="gray")
plt.subplot(6,10, featuremap+2) # sets the number of feature maps to show on each row and column
#plt.title(str(i)+': Original Image') # displays the feature map number
plt.imshow(image_input[i].squeeze(), cmap="gray")
plt.show()
x = tf.placeholder(tf.float32, (None, 32, 32, input_depth))
conv1_W=t_list["conv1_W"]
conv1_b=t_list["conv1_b"]
conv1_c = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID') + conv1_b
# SOLUTION: Activation.
conv1_r = tf.nn.relu(conv1_c)
# SOLUTION: Pooling. Input = 28x28x6. Output = 14x14x6.
conv1 = tf.nn.max_pool(conv1_r, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
# SOLUTION: Layer 2: Convolutional. Output = 10x10x16.
conv2_W = t_list["conv2_W"]
conv2_b = t_list["conv2_b"]
conv2_c = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID') + conv2_b
# SOLUTION: Activation.
conv2_r = tf.nn.relu(conv2_c)
# SOLUTION: Pooling. Input = 10x10x16. Output = 5x5x16.
conv2 = tf.nn.max_pool(conv2_r, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
# SOLUTION: Flatten. Input = 5x5x16. Output = 400.
fc0 = flatten(conv2)
fc1_W = t_list["fc1_W"]
fc1_b = t_list["fc1_b"]
fc1 = tf.matmul(fc0, fc1_W) + fc1_b
# SOLUTION: Activation.
fc1 = tf.nn.relu(fc1)
# SOLUTION: Layer 4: Fully Connected. Input = 120. Output = 84.
fc2_W = t_list["fc2_W"]
fc2_b = t_list["fc2_b"]
fc2 = tf.matmul(fc1, fc2_W) + fc2_b
# SOLUTION: Activation.
fc2 = tf.nn.relu(fc2)
fc3_W = t_list["fc3_W"]
fc3_b = t_list["fc3_b"]
# SOLUTION: Layer 5: Fully Connected. Input = 84. Output = 10.
logits = tf.matmul(fc2, fc3_W) + fc3_b
with tf.Session() as sess:
saver.restore(sess, './lenet')
outputFeatureMap(img, conv1_c)#,activation_min=-5, activation_max=5 )
with tf.Session() as sess:
saver.restore(sess, './lenet')
outputFeatureMap(img, conv2_r)#,activation_min=0, activation_max=5 )
Discuss how you used the visual output of your trained network's feature maps to show that it had learned to look for interesting characteristics in traffic sign images
Answer:
Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.